package com.bdsoft.actions.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.nio.charset.StandardCharsets;


public class MyWebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

        // 判断是否是文本帧
        if (frame instanceof BinaryWebSocketFrame) {
            BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
            ByteBuf content = binaryFrame.content();

            System.out.println("Received binary data, size: " + content.readableBytes() + " bytes");

            WebSocketChannelManager.broadcast(new BinaryWebSocketFrame(content.retain()));
            // 如果是图片数据，可以这样发送：
            // byte[] imageBytes = new byte[content.readableBytes()];
            // content.readBytes(imageBytes);
            // ByteBuf buffer = Unpooled.wrappedBuffer(imageBytes);
            // ctx.channel().writeAndFlush(new BinaryWebSocketFrame(buffer));
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String clientId = ctx.channel().id().toString();
        WebSocketChannelManager.addChannel(clientId, ctx.channel());
        System.out.println("客户端连接成功: " + ctx.channel().remoteAddress());

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String clientId = ctx.channel().id().toString();
        WebSocketChannelManager.removeChannel(clientId);
        System.out.println("客户端断开连接: " + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("WebSocket握手或通信异常: " + cause.getMessage());
        ctx.close();
    }
}